package org.yysd.util;

import org.yysd.pojo.CustomPagePanelConfig;
import org.yysd.widget.CustomPagePanel;

import javax.swing.table.DefaultTableModel;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class WidgetUtil {

    public static Map<String, String> getMap(DefaultTableModel model) {
        Map<String, String> headerMap = new LinkedHashMap<>();
        for (int row = 0; row < model.getRowCount(); row++) {
            String key = model.getValueAt(row, 0).toString();
            String value = model.getValueAt(row, 1).toString();
            headerMap.put(key, value);
        }
        return headerMap;
    }

    public static void setMap(DefaultTableModel model, Map<String, String> dataMap) {
        if (dataMap == null) return;
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        Iterator<Map.Entry<String, String>> iterator = dataMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> next = iterator.next();
            ;
            model.addRow(new String[]{next.getKey(), next.getValue()});
        }
    }

    public static CustomPagePanelConfig getCustomPagePanelConfig(CustomPagePanel curPanel) {
        // 获取JTable的数据到Map
        Map<String, String> headerMap = WidgetUtil.getMap(curPanel.model);
        Map<String, String> parameMap = WidgetUtil.getMap(curPanel.model_1);
        String httpMethod = curPanel.comboBox.getSelectedItem().toString();

        CustomPagePanelConfig config = new CustomPagePanelConfig();
        config.tabId = curPanel.tabId;
        config.tabName = curPanel.tabName;
        config.basicUrl = curPanel.textArea_url.getText();
        config.requestUrl = curPanel.textArea.getText();
        config.heaherMap = headerMap;
        config.parameMap = parameMap;
        config.requestBody = curPanel.rTextArea.getText();
        config.responseBody = curPanel.rSyntaxTextArea.getText();
        config.statusText = curPanel.statusLabel.getText();
        config.requestMethod = httpMethod;
        return config;
    }


    public static CustomPagePanel initCustomPagePanel(CustomPagePanel customPagePanel, CustomPagePanelConfig config) {
        customPagePanel.textArea_url.setText(config.basicUrl);
        customPagePanel.textArea.setText(config.requestUrl);
        customPagePanel.rTextArea.setText(config.requestBody);
        customPagePanel.rSyntaxTextArea.setText(config.responseBody);
        customPagePanel.statusLabel.setText(config.statusText);
        customPagePanel.comboBox.setSelectedItem(config.requestMethod);
        customPagePanel.tabName = config.tabName;
        return customPagePanel;
    }
}
